import { CloudRequest } from '../request/customer-request.js'
const DateUtil = require('../utils/dateUtil.js')
let App = getApp()
class CouponModel extends CloudRequest {
    /**
     * 获取商家账户信息
     * 
     */
    async getCoupon(coupon) {
       let res = await  this.request({
            url: "getCoupon",
            data:{
                coupon:coupon
            }
        })
        return res.result.data.data
    }
    async updateCoupon(coupon, couponId){
      let res = await  this.request({
            url:"updateCoupon",
            data:{
                coupon:coupon,
                couponId:couponId
            }
        })
        return res.result.data.data
    }
    async createCoupon(coupon){
        let res = await this.request({
            url:"addCoupon",
            data:{
                coupon:coupon,
            }
        })
        return res.result.data.data
    }
    async deleteCoupon(couponId){
        let res = await this.request({
            url:"deleteCoupon",
            data:{
                couponId:couponId
            }
        })
        return res.result.data.data
    }
    // 创建count张优惠券
    async  createCoupon(coupon,count){
        let res = {}
        if(count){
            for(let i=0;i<count;i++){
            res =   await Coupon.createCoupon(coupon)
            }
        }else{
            res = await Coupon.createCoupon(coupon)
        }
        let coupons = res.result.data.data 
        return coupons 
    }

    // 获取可使用的优惠券
    async  getUsefulCoupons(){
        let coupon = {
            // openid : App.globalData.openId
            openid : 'oOqKc5bD6CYDthUAgKF6kWuPfCbQ'
        }
        let res = await this.getCoupon(coupon)
        let coupons =  this.checkCoupon(res)
        return coupons
    }

    checkDay(startDay, endDay){
        let start = new Date(startDay).getTime()
        let end = new Date(endDay).getTime()
        let today = new Date().getTime()

        if(start < today && today < end){
            return true
        }else{
            return false
        }
    }
    checkCoupon(coupons){
        let arr = coupons
        for (var i = arr.length - 1; i >= 0; i--) {
            if(!this.checkDay(arr[i].start_time, arr[i].end_time)) {
                arr.splice(i, 1);
            }
        }
        return arr
    }

    
}

export { CouponModel }
